Get unique values

This notebook gets the unique values from a specified field in a GRASS vector map.

This notebook uses GRASS GIS (7.0.4), and must be run inside of a GRASS environment (start the jupyter notebook server from the GRASS command line). GRASS GIS

Required packages

Variable declarations

vector_map – GRASS vector map to get unique values from
value_field – field in 'vector_map' to get unique values from
output_filename – path to export a list of unique values in csv format


In [4]:
vector_map = 'landcover_corine'

In [5]:
value_field = 'value'

In [22]:
output_filename = ""

Import statements


In [9]:
import pandas
import numpy as np

import grass.script as gscript
from grass.pygrass.vector import VectorTopo
from grass.pygrass.vector.table import DBlinks

Function declarations

connect to attribute table


In [7]:
def connectToAttributeTable(map):
    vector = VectorTopo(map)
    vector.open(mode='r')
    dblinks = DBlinks(vector.c_mapinfo)
    link = dblinks[0]
    return link.table()

Get unique values

query to attribute table


In [16]:
table = connectToAttributeTable(map=vector_map)
table.filters.select(value_field)
cursor = table.execute()
result = np.array(cursor.fetchall())
cursor.close()

get unique values


In [17]:
data = np.unique(result)

In [18]:
data


Out[18]:
array([1110, 1120, 1210, 1220, 1240, 1420, 2110, 2210, 2311, 2312, 2313,
       2315, 2316, 2400, 2410, 2420, 2430, 3112, 3113, 3114, 3120, 3121,
       3122, 3123, 3124, 3126, 3127, 3131, 3211, 3212, 3216, 3220, 3321,
       3322, 3331, 3332, 5110])

export unique values to csv


In [21]:
np.savetxt(output_filename, data)